//
//  NSIndexSet+ZXAvoidCrash.m
//  ZXAvoidCrash
//
//  Created by 朱新明 on 2023/3/23.
// 索引集，是一个唯一的（index不可重复的），有序的（添加的index会按索引大小在集合内部自己排序），无符号整数的集合。

#import "NSIndexSet+ZXAvoidCrash.h"
#import "ZXAvoidCrashRuntime.h"
#import "ZXAvoidCrashReport.h"

@implementation NSIndexSet (ZXAvoidCrash)

+ (void)zx_avoidCrashExchangeMethod
{
    ///空索引集，只有一个index的索引集
//    Class _NSCachedIndexSet = NSClassFromString(@"_NSCachedIndexSet");

    ///超过一个index的索引集
    Class NSIndexSet = NSClassFromString(@"NSIndexSet");
    [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:NSIndexSet originalSelector:@selector(initWithIndexesInRange:) swizzledSelector:@selector(zx_initWithIndexesInRange:)];
}


#pragma mark -initWithIndexesInRange:

/*
 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSIndexSet initWithIndexesInRange:]: Range {9223372036854775807, 1} exceeds maximum index value of NSNotFound - 1'
 */

- (instancetype)zx_initWithIndexesInRange:(NSRange)range
{
    id instance = nil;
    @try {
        instance = [self zx_initWithIndexesInRange:range];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception];
    } @finally {
        return instance;
    }
}
@end



@implementation NSMutableIndexSet (ZXAvoidCrash)

+ (void)zx_avoidCrashExchangeMethod
{
    ///可变索引集
    Class NSIndexSet = NSClassFromString(@"NSMutableIndexSet");
    [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:NSIndexSet originalSelector:@selector(addIndexesInRange:) swizzledSelector:@selector(zx_addIndexesInRange:)];
}


#pragma mark -addIndexesInRange:

/*
 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableIndexSet addIndexesInRange:]: Range {9223372036854775807, 1} exceeds maximum index value of NSNotFound - 1'
 */
- (void)zx_addIndexesInRange:(NSRange)range{
    @try {
        [self zx_addIndexesInRange:range];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception];
    } @finally {
    }
}
@end
